package com.filldream.sun.core;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * PKCS7解密工具
 * @author RickSun
 */
public class PKCS7Util {
    static Charset CHARSET = Charset.forName("utf-8");
    static int BLOCK_SIZE = 32;

    public PKCS7Util() {
    }

    public static byte[] encode(int count) {
        int amountToPad = BLOCK_SIZE - count % BLOCK_SIZE;
        if (amountToPad == 0) {
            amountToPad = BLOCK_SIZE;
        }

        char padChr = chr(amountToPad);
        String tmp = new String();

        for(int index = 0; index < amountToPad; ++index) {
            tmp = tmp + padChr;
        }

        return tmp.getBytes(CHARSET);
    }

    public static byte[] decode(byte[] decrypted) {
        int pad = decrypted[decrypted.length - 1];
        if (pad < 1 || pad > 32) {
            pad = 0;
        }

        return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
    }

    static char chr(int a) {
        byte target = (byte)(a & 255);
        return (char)target;
    }
}